﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AllInOne;
using AllInOne.Classes;
using AllInOne.Entity;
using AllInOne.HDI.CRT_591_M001;
using AllInOne.Models;
using AllInOne.UserControls;
using RestSharp;

namespace AllInOne.MainPages
{
    /// <summary>
    /// 还卡的逻辑
    /// </summary>
    public partial class IndexReturnPage : Page
    {
        Window ShowPrint = new Window();
        public IndexReturnPage()
        {
            InitializeComponent();
        }

        private MainWindow parent;

        private UInt32 Hdle = 0;

        public IndexReturnPage(MainWindow parent)
        {
            InitializeComponent();
            //读取卡的时候，是先进行，然后修改还卡流程，
            this.parent = parent;
            Hdle = parent.Hdle;
        }

        private void BtnBackToIndex_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.parent.ResetIndex();
        }

        private void BtnQmhz_MouseUp(object sender, MouseButtonEventArgs e)
        {
            //this.parent.ChooseBusiness(BusinessType.QMHZ);
            this.parent.Choose_Business(EnterBusinessType.LRXXZK);
        }
        private void BtnYsbz_MouseUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                MessageBox.Show("开始打印测试出门条");
                ////打印出门条：
                //ExitViewModel exitViewModel = new ExitViewModel();
                //string IdentityNum = "410325199205280511";
                //if (!string.IsNullOrEmpty(IdentityNum) && IdentityNum.Length == 18)
                //{
                //    if (SystemParam.HiddenBirthdy)//处理是否隐藏生日
                //    {
                //        if (IdentityNum.Length == 18)
                //        {
                //            //7-14是生日位
                //            string tempStr = IdentityNum.Substring(0, 10) + "****" + IdentityNum.Substring(14, 4);
                //            IdentityNum = tempStr;
                //        }
                //    }
                //}
                //exitViewModel.ID = IdentityNum;
                //exitViewModel.Name = "杨智可";
                //exitViewModel.PlateNo = "蒙D12345";
                //exitViewModel.PrintDateTime = System.DateTime.Now;
                //PrintExitControl print = new PrintExitControl(exitViewModel);
                //this.border.Child = print;
                //PrintHelper.Print(print, "出门证");

                #region 打印数据
                List<string> InfoList = new List<string>();
                InfoList.Add("出门证");
                InfoList.Add("蒙D12345");
                InfoList.Add("杨智可");
                InfoList.Add("410325190001020511");
                InfoList.Add(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                Printer printer1 = new Printer
                {
                    LoginID = 12,
                    InfoList = InfoList
                };
                printer1.Print();
                //MessageBox.Show("打印完成");
                LogHelper.WriteLog("打印出门证：完成！");
                #endregion





                //调用另一种方式打印出门证

            }
            catch (Exception ex)
            {
                MessageBox.Show("打印出门条出错：" + ex.ToString());
            }
        }

        private void PrintWeigh(AuthModel authModel)
        {
            PrintView print = new PrintView(authModel, SystemParam.CountDownPrint);
            print.ShowDialog();
        }
        private void BtnShhz_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.parent.ChooseBusiness(BusinessType.SHHZ);
        }

        private void BtnCcsl_MouseUp(object sender, MouseButtonEventArgs e)
        {

        }

        private void BtnDyzj_MouseUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                CardModel authModel = ShowReadCard();
                if (authModel != null && !string.IsNullOrEmpty(authModel.CardNumber))
                {
                    BackICardByCardNum(authModel.CardNumber);
                }
                else
                {
                    MessageBox.Show("还卡失败,未读取到卡号,请取出你的卡片！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("还卡出错！");
                SimpleConsole.WriteInfo("出厂还卡错误" + ex.ToString(), this);
            }
        }

        /// <summary>
        /// 根据卡号归还IC卡
        /// </summary>
        /// <param name="ICCardNum">卡号</param>
        public void BackICardByCardNum(string ICCardNum)
        {
            try
            {
                string msg = "";
                SimpleConsole.WriteInfo("还卡操作卡号" + ICCardNum, this);

                string url = ServiceWebApi.BASE_URL + "SSMachine/BackICardByCardNum";
                var client = new RestClient(url);
                var request = new RestRequest(Method.POST);
                //request.AddHeader("Accept", "*/*");//‘可省略
                request.AddParameter("CardNum", ICCardNum);
                var response = client.Execute(request);
                if (!string.IsNullOrEmpty(response.Content))
                {
                    SimpleConsole.WriteOprateLog($"【{ICCardNum}】还卡返回信息" + response.Content, null);
                    BackInfo backInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<BackInfo>(response.Content);
                    if (backInfo.code == 200)//还卡，并将出门证打印出来
                    {
                        ExitViewModel exitViewModel = Newtonsoft.Json.JsonConvert.DeserializeObject<ExitViewModel>(backInfo.data.ToString());
                        string IdentityNum = exitViewModel.IdentityNum;
                        if (!string.IsNullOrEmpty(IdentityNum) && IdentityNum.Length == 18)
                        {
                            if (SystemParam.HiddenBirthdy)//处理是否隐藏生日
                            {
                                if (IdentityNum.Length == 18)
                                {
                                    //7-14是生日位
                                    string tempStr = IdentityNum.Substring(0, 10) + "****" + IdentityNum.Substring(14, 4);
                                    IdentityNum = tempStr;
                                }
                            }
                        }

                        //并将卡传到收卡箱中 "移卡到盒里成功"
                        if (GrantCardClient.MoveCardToRecycleBin(Hdle, "00", out msg))
                        {
                            //软件中的打印
                            List<string> InfoList = new List<string>();
                            InfoList.Add("出门证");
                            InfoList.Add(exitViewModel.Plate);
                            InfoList.Add(exitViewModel.RegName);
                            InfoList.Add(IdentityNum);
                            InfoList.Add(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            try
                            {
                                Printer printer1 = new Printer
                                {
                                    LoginID = 12,
                                    InfoList = InfoList
                                };
                                //调用打印
                                printer1.Print();
                                LogHelper.WriteLog("打印出门证：完成！");
                            }
                            catch (Exception ex)
                            {
                                Log.Info($"打印出门证出错：" + ex.ToString());
                            }
                            //进卡口关闭
                            try
                            {
                                if (!GrantCardClient.NoCardIn(Hdle, "00", out msg))
                                {
                                    Log.Info($"进卡口关闭失败！");
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.Info($"进卡口关闭出错：" + ex.ToString());
                            }
                            this.parent.ShowText("还卡成功！");
                            this.parent.PlayVioceQueue.Enqueue("还卡成功。");
                            return;
                        }
                        //还卡失败--将卡推送到最前面。
                        if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                        {
                            MessageBox.Show("还卡失败，请取走你的卡片!");
                            return;
                        }
                    }
                    else if (backInfo.code == 201)
                    {
                        //将错误信息组合起来传到前台
                        switch (backInfo.data.ToString())
                        {
                            case "1"://"未识别的卡,不能进行还卡"
                            case "3"://"此卡已经完成称重,可以还卡,收回到卡槽,但更新数据库卡注册信息失败";
                            case "4"://"此卡未完成称重,不能还卡,卡重新从卡槽吐出";
                                //做一个兼容：【已归还的卡,不能重复还卡】2023年4月20日
                                if (backInfo.message != null && backInfo.message == "已归还的卡,不能重复还卡")
                                {
                                    if (GrantCardClient.MoveCardToRecycleBin(Hdle, "00", out msg))
                                    {
                                        this.parent.ShowText("还卡成功！");
                                        this.parent.PlayVioceQueue.Enqueue("还卡成功。");
                                        this.parent.ResetIndex();
                                        return;
                                    }
                                }
                                if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                                {
                                    this.parent.ShowText("还卡失败");
                                    this.parent.PlayVioceQueue.Enqueue("还卡失败");
                                    MessageBox.Show($"还卡失败,{ backInfo.message} 请取走你的卡片!");
                                }
                                break;
                            case "5"://此卡没有过车记录,直接还卡,不打印出门证
                            case "6"://卡信息是厂内流转货物,直接还卡,不打印出门证
                            case "9"://此卡没有过车记录,直接还卡,不打印出门证
                                if (GrantCardClient.MoveCardToRecycleBin(Hdle, "00", out msg))
                                {
                                    this.parent.ShowText("还卡成功！");
                                    this.parent.PlayVioceQueue.Enqueue("还卡成功。"); 
                                    this.parent.ResetIndex();
                                    return;
                                }
                                else
                                {
                                    //卡推送卡机失败，则吐出来
                                    if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                                    {
                                        this.parent.ShowText("还卡失败");
                                        this.parent.PlayVioceQueue.Enqueue("还卡失败,移动回收盒失败");
                                    }
                                }
                                break;
                            //case "7"://此卡已经完成称重,可以还卡
                            //break;
                            case "8":
                                if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                                {
                                    this.parent.ShowText("还卡失败");
                                    this.parent.PlayVioceQueue.Enqueue(backInfo.message);
                                    return;
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("连接服务器失败！");
                    //还卡失败--将卡推送到最前面。
                    if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                    {
                        MessageBox.Show("还卡失败，请取走你的卡片!");
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteError("还卡失败出错" + ex.ToString(), null);
            }
            this.parent.ResetIndex();
        }
        
        private void BtnShuaKaChaXun_MouseUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                CardModel authModel = ShowReadCard();
                MessageBox.Show("卡号为:" + authModel.CardNumber);
                //下一步应该到新的页面上，显示此次过车的信息，
            }
            catch (Exception)
            {

            }
        }
        /// <summary>
        /// 弹出刷卡窗体并返回值
        /// </summary>
        /// <returns></returns>
        private CardModel ShowReadCard()
        {
            ReadCard readCard = new ReadCard(parent.Hdle);
            bool? result = readCard.ShowDialog();
            if (result == true)
            {
                return new CardModel() { AuthType = readCard.AuthType, CardNumber = readCard.AuthCode };
            }
            else
                return null;
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (SystemParam.TestPage == 1)
            {
                btnYsbz.Visibility = Visibility.Visible;
            }
            if (SystemParam.TestPage == 10)
            {
                btnShuaKaChaXun.Visibility = Visibility.Visible;//查询卡号
            }
            Hdle = parent.Hdle;//自助机串口句柄
        }
    }
}
